package com.scoressystem.controller;

import com.scoressystem.pojo.Teacher;
import com.scoressystem.service.TeacherService;
import com.scoressystem.utils.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/teacher")
public class TeacherController{

    @Resource
    TeacherService teacherService;

    @RequestMapping("/login")
    public Results login(String userName, String password,
                         String userCode, HttpSession session) {

        Object sysCodeObj = session.getAttribute("systemCode");
        if (sysCodeObj == null) {
            return new Results<>("0", "验证码已过期，请刷新重试");
        }
        String sysCode = sysCodeObj.toString();
        if (!sysCode.equalsIgnoreCase(userCode)) {
            return new Results<>("0", "验证码错误");
        }
        Teacher teacher = teacherService.getTeacherByName(userName, password);
        if (teacher == null){
            return new Results<>("2", "用户名或密码错误");
        } else {
            session.setAttribute("nowusername", userName);
            return new Results<>("1", "登录成功", teacher,0);
        }
    }

    @PostMapping("/updatePwd")
    public Results updatePwd(HttpSession session, String pwd, String pwd1, String pwd2) {
        String userName = (String) session.getAttribute("nowusername");
        Teacher teacherByName = teacherService.getTeacherByName(userName, pwd);
        if (teacherByName == null) {
            return new Results<>("1", "原密码错误");
        }
        if (!pwd1.equals(pwd2)) {
            return new Results<>("2", "两次新密码输入不一致");
        }
        if (pwd.equals(pwd1)){
            return new Results<>("3", "新密码不能与原密码相同");
        }
        int i = teacherService.updatePwd(userName, pwd1);
        if (i > 0) {
            session.invalidate();
            return new Results<>("0", "密码修改成功，请重新登录");
        } else {
            return new Results<>("5", "密码修改失败，请稍后重试");
        }
    }
}
